<template>
  <a-modal
    v-if="visible"
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="mode === 'view' ? null : undefined"
  >
    <!-- 新增/编辑模式 -->
    <template v-if="mode === 'add'">
      <a-spin :spinning="confirmLoading">
        <a-form>
          <!-- 条件选择区域 -->
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label="学期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-select-xueqi placeholder="请选择学期" v-model="queryParam.semid"></j-select-xueqi>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="年级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-select-grade placeholder="请选择年级" v-model="queryParam.gradeid"></j-select-grade>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="专业部" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-select-zyb placeholder="请选择专业部" v-model="queryParam.falid" @input="zybChange"></j-select-zyb>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="专业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-select-zy-by-zyb placeholder="请选择专业" ref="zyByZyb" v-model="queryParam.specid" @input="zyChange"></j-select-zy-by-zyb>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="班级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-select-banji-by-zy placeholder="请选择班级" ref="banjiByZy" v-model="queryParam.xzbid"></j-select-banji-by-zy>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="预警类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="queryParam.warningReason" placeholder="请选择预警类型" allowClear>
                  <a-select-option value="1">学分预警</a-select-option>
                  <a-select-option value="2">不及格门数预警</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- 学生列表 -->
          <a-table
            :columns="studentColumns"
            :dataSource="studentList"
            rowKey="xh"
            :rowSelection="{ selectedRowKeys: selectedStudentKeys, onChange: onSelectChange }"
            :pagination="false"
            size="small"
            style="margin-bottom: 16px"
          />

          <!-- 预警信息 -->
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label="预警等级" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="model.warningLevel" placeholder="请选择预警等级" allowClear>
                  <a-select-option value="1">高</a-select-option>
                  <a-select-option value="2">中</a-select-option>
                  <a-select-option value="3">低</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="model.contactPerson" placeholder="请输入联系人" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="model.contactInfo" placeholder="请输入联系方式" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="整改要求" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-textarea v-model="model.rectificationRequirements" placeholder="请输入整改要求" :rows="4" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </template>

    <!-- 查看模式 -->
    <template v-else-if="mode === 'view'">
      <a-table
        :columns="viewColumns"
        :dataSource="viewData"
        :pagination="viewPagination"
        :loading="viewLoading"
        @change="handleViewPageChange"
        rowKey="id"
        size="small"
      />
    </template>
  </a-modal>
</template>

<script>
import { getWarningDetail, getWarningStudentsByCredits, getWarningStudentsBySubjects } from '@/api/common/manage'
import JSelectXueqi from '@/components/kwglbiz/JSelectXueqi'
import JSelectGrade from '@/components/kwglbiz/JSelectGrade'
import JSelectZyb from '@/components/kwglbiz/JSelectZyb'
import JSelectZyByZyb from '@/components/kwglbiz/JSelectZyByZyb'
import JSelectBanjiByZy from '@/components/kwglbiz/JSelectBanjiByZy'

export default {
  name: 'VeJwCjyjModal',
  components: {
    JSelectXueqi,
    JSelectGrade,
    JSelectZyb,
    JSelectZyByZyb,
    JSelectBanjiByZy
  },
  data() {
    return {
      title: '操作',
      visible: false,
      confirmLoading: false,
      mode: 'add', // add-新增模式, view-查看模式

      // 查询参数
      queryParam: {
        semid: '',
        gradeid: '',
        zybid: '',
        zyid: '',
        bjid: '',
        warningReason: '',
        falid: '',
        specid: '',
        xzbid: ''
      },

      // 表单数据
      model: {
        warningLevel: undefined,
        contactPerson: '',
        contactInfo: '',
        rectificationRequirements: ''
      },

      // 布局配置
      labelCol: { xs: { span: 24 }, sm: { span: 5 } },
      wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },

      // 学生列表相关
      studentList: [],
      selectedStudentKeys: [],
      studentColumns: [
        { title: '学号', dataIndex: 'xh', align: 'center' },
        { title: '姓名', dataIndex: 'xm', align: 'center' },
        { title: '专业', dataIndex: 'zy', align: 'center' },
        { title: '班级', dataIndex: 'bj', align: 'center' },
        { title: '不及格学分', dataIndex: 'totalFailedCredits', align: 'center' },
        { title: '不及格门数', dataIndex: 'failedSubjectsCount', align: 'center' }
      ],

      // 查看视图相关
      viewData: [],
      viewColumns: [
        { title: '学号', dataIndex: 'xh', align: 'center' },
        { title: '姓名', dataIndex: 'xm', align: 'center' },
        { title: '专业', dataIndex: 'zy', align: 'center' },
        { title: '班级', dataIndex: 'bj', align: 'center' },
        { title: '预警等级', dataIndex: 'warningLevel', align: 'center',
          customRender: (text) => {
            const levels = { '1': '高', '2': '中', '3': '低' }
            return levels[text] || text
          }
        },
        { title: '预警类型', dataIndex: 'warningReason', align: 'center',
          customRender: (text) => {
            const types = { '1': '学分预警', '2': '不及格门数预警' }
            return types[text] || text
          }
        }
      ],
      viewPagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      viewLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        semid: {rules: [{ required: true, message: '请选择学期!' }]},
        gradeid: {rules: [{ required: true, message: '请选择年级!' }]},
        falid: {rules: [{ required: true, message: '请选择专业部!' }]},
        specid: {rules: [{ required: true, message: '请选择专业!' }]},
        xzbid: {rules: [{ required: true, message: '请选择班级!' }]},
        yjlx: {rules: [{ required: true, message: '请选择预警类型!' }]},
        yjdj: {rules: [{ required: true, message: '请选择预警等级!' }]},
        lxr: {rules: [{ required: true, message: '请输入联系人!' }]},
        lxfs: {rules: [{ required: true, message: '请输入联系方式!' }]}
      },
      url: {
        add: "/kwgl/veJwCjyj/add",
        edit: "/kwgl/veJwCjyj/edit",
      }
    }
  },
  watch: {
    'queryParam.semid': 'tryFetchStudents',
    'queryParam.gradeid': 'tryFetchStudents',
    'queryParam.falid': 'tryFetchStudents',
    'queryParam.specid': 'tryFetchStudents',
    'queryParam.xzbid': 'tryFetchStudents',
    'queryParam.warningReason': 'tryFetchStudents',
  },
  methods: {
    add() {
      this.mode = 'add'
      this.queryParam = {
        semid: '',
        gradeid: '',
        zybid: '',
        zyid: '',
        bjid: '',
        warningReason: '',
        falid: '',
        specid: '',
        xzbid: ''
      }
      this.model = {
        warningLevel: undefined,
        contactPerson: '',
        contactInfo: '',
        rectificationRequirements: ''
      }
      this.studentList = []
      this.selectedStudentKeys = []
      this.visible = true
      this.title = '新增预警信息'
    },
    view(record) {
      this.mode = 'view'
      this.visible = true
      this.title = '查看预警学生'
      this.loadWarningDetail(record.id)
    },
    async loadWarningDetail(id) {
      this.viewLoading = true
      try {
        const result = await getWarningDetail({ id: id })
        if (result.success) {
          this.viewData = result.result.records || []
          this.viewPagination.total = result.result.total
        }
      } finally {
        this.viewLoading = false
      }
    },
    edit(record) {
      this.mode = 'add'
      this.visible = true
      this.title = '编辑预警信息'
      
      // 设置表单数据
      this.model = {
        id: record.id,
        warningLevel: record.warningLevel,
        contactPerson: record.contactPerson,
        contactInfo: record.contactInfo,
        rectificationRequirements: record.rectificationRequirements
      }
      
      // 设置查询参数
      this.queryParam = {
        semid: record.semid,
        gradeid: record.gradeid,
        zybid: record.zybid,
        zyid: record.zyid,
        bjid: record.bjid,
        warningReason: record.warningReason
      }
      
      // 加载学生信息
      this.loadWarningDetail(record.id)
    },
    handleSemesterChange() {
      this.queryParam.gradeid = ''
      this.queryParam.zybid = ''
      this.queryParam.zyid = ''
      this.queryParam.bjid = ''
    },
    handleGradeChange() {
      this.queryParam.zybid = ''
      this.queryParam.zyid = ''
      this.queryParam.bjid = ''
    },
    handleZybChange(value) {
      this.queryParam.zyid = ''
      this.queryParam.bjid = ''
      if (this.$refs.zyByZyb) {
        this.$refs.zyByZyb.initDictData(value)
      }
    },
    handleZyChange(value) {
      this.queryParam.bjid = ''
      if (this.$refs.banjiByZy) {
        this.$refs.banjiByZy.initDictData(value)
      }
    },
    handleOk() {
      if (this.mode === 'view') {
        this.close()
        return
      }

      if (this.selectedStudentKeys.length !== 1) {
        this.$message.warning('请选择一名学生！')
        return
      }
      if (!this.model.warningLevel) {
        this.$message.warning('请选择预警等级！')
        return
      }
      if (!this.model.contactPerson || !this.model.contactInfo) {
        this.$message.warning('请填写联系人和联系方式！')
        return
      }

      // 获取选中学生对象
      const student = this.studentList.find(s => s.xh === this.selectedStudentKeys[0])
      if (!student) {
        this.$message.warning('学生信息异常！')
        return
      }
      // 组装VeJwCjyj对象，字段与后端一致
      const veJwCjyjObj = {
        xh: student.xh,
        xm: student.xm,
        zy: student.zy,
        bj: student.bj,
        warningReason: Number(this.queryParam.warningReason),
        warningLevel: Number(this.model.warningLevel),
        rectificationRequirements: this.model.rectificationRequirements,
        contactPerson: this.model.contactPerson,
        contactInfo: this.model.contactInfo
      }
      this.$emit('ok', veJwCjyjObj)
      this.close()
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.mode = 'add'
      this.queryParam = {
        semid: '',
        gradeid: '',
        zybid: '',
        zyid: '',
        bjid: '',
        warningReason: '',
        falid: '',
        specid: '',
        xzbid: ''
      }
      this.model = {
        warningLevel: undefined,
        contactPerson: '',
        contactInfo: '',
        rectificationRequirements: ''
      }
      this.studentList = []
      this.selectedStudentKeys = []
      this.viewData = []
      this.visible = false
    },
    handleViewPageChange(pagination) {
      this.viewPagination.current = pagination.current
    },
    zybChange(value) {
      this.$refs.zyByZyb.initDictData(value);
      this.form.setFieldsValue({specid:undefined});
      this.form.setFieldsValue({xzbid:undefined});
    },
    zyChange(value) {
      this.$refs.banjiByZy.initDictData(value);
      this.form.setFieldsValue({xzbid:undefined});
    },
    async tryFetchStudents() {
      const { semid, gradeid, falid, specid, xzbid, warningReason } = this.queryParam
      if (semid && gradeid && falid && specid && xzbid && warningReason) {
        console.log('查询参数', this.queryParam)
        let result
        const params = { semid, gradeid, falid, specid, xzbid }
        if (warningReason === '1') {
          result = await getWarningStudentsByCredits(params)
        } else if (warningReason === '2') {
          result = await getWarningStudentsBySubjects(params)
        }
        console.log('接口返回', result)
        console.log('赋值前', this.studentList)
        if (result && result.success) {
          this.studentList = (result && result.result && Array.isArray(result.result.records)) ? result.result.records : []
          console.log('赋值后', this.studentList)
          this.selectedStudentKeys = []
        } else {
          this.studentList = []
          this.selectedStudentKeys = []
        }
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedStudentKeys = selectedRowKeys;
    },
  }
}
</script>

<style scoped>
.modal-wrapper {
  /* 可以添加样式 */
}
</style> 